package com.tenement.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.tenement.common.Axios;
import com.tenement.common.GlobalConstants;
import com.tenement.enums.RespBusiness;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@RequestMapping("file")
@Api(tags = "文件上传")
@Slf4j
@RequiredArgsConstructor
public class FileController {

    private final GlobalConstants constants;

    SimpleDateFormat dateUri = new SimpleDateFormat("yyyy/MM/dd/");

    @SneakyThrows
    @ApiOperation(value = "上传文件")
    @PostMapping("/uploadx")
    public Axios handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Axios.error(RespBusiness.FILE_IS_EMPTY);
        }
        String format = dateUri.format(new Date());
        File folder = new File(constants.getUploadDir() + format);
        String extName = FileUtil.extName(file.getOriginalFilename());
        String fileName = IdUtil.fastSimpleUUID() + "." + extName;
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        file.transferTo(new File(folder, fileName));
        return Axios.success(format + fileName);
    }




}
